<template>
    <div class="activitie-box" @click="goInDetail(activityData.id)">
        <div class="activitie-title-box">
            <p class="activitie-title">{{ activityData.subject }}</p>
        </div>
        <div class="flex activitie-address">
            <p>活动地点：</p>
            <p>{{ activityData.address }}</p>
        </div>
        <div class="flex activitie-activity-time">
            <p>活动时间：</p>
            <p>{{ formattedDate(activityData.activityStart) }} - {{ formattedDate(activityData.activityEnd) }}</p>
        </div>
        <div class="flex activitie-join-time">
            <p>报名时间：</p>
            <p>{{ formattedDate(activityData.joinStart) }} - {{ formattedDate(activityData.joinEnd) }}</p>
        </div>
        <div class="activitie-button-box">
            <!-- <el-button :type="buttonType" class="activitie-button" @click="goActivitie(e)">活动{{ activityData.statusName
            }}</el-button> -->
            <div v-show="activityData.joinStatus === 0">
                <el-button class="activitie-button">名额已满</el-button>
                <p style="font-size: 0.52vw">
                    非常抱歉，名额不足，欢迎下次再来
                </p>
            </div>
            <div v-show="activityData.joinStatus === 2">
                <el-button class="activitie-button" @click="handleOtherAction(activityData.id)">
                    提交报名信息
                </el-button>
                <p style="font-size: 0.52vw">
                    您已抢到名额，15分钟内有效，请尽快提交报名信息
                </p>
            </div>
            <div v-show="activityData.joinStatus === 3">
                <el-button class="activitie-button">排队中</el-button>
                <p style="font-size: 0.52vw">活动热门请等待</p>
            </div>
            <div v-show="activityData.joinStatus === 4">
                <el-button class="activitie-button" @click="tosee(activityData.id)">查看报名</el-button>
                <p style="font-size: 0.52vw">您已报名成功</p>
            </div>
            <div v-show="activityData.joinStatus === 5">
                <el-button @click="openDialog(activityData.id)">抢名额</el-button>
            </div>
            <div v-show="activityData.joinStatus === -1">
                <el-button class="activitie-button" @click="eventEnded">报名已结束</el-button>
            </div>
            <div v-show="activityData.joinStatus === -2">
                <el-button class="activitie-button" @click="eventEnded">活动已结束</el-button>
            </div>
        </div>

        <el-dialog :append-to-body="true" title="欢迎报名" :visible.sync="dialogVisible" width="30%"
            :before-close="handleClose" center>
            <el-form :model="activityInfo" :rules="rules" ref="activityInfo" label-width="100px" class="demo-ruleForm">
                <el-form-item label="姓名" prop="name" size="samll" class="inpbox">
                    <el-input v-model="activityInfo.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone" v-model="activityInfo.phone" class="inpbox">
                    <el-input v-model.number="activityInfo.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender" class="inpbox">
                    <el-radio-group v-model="activityInfo.gender">
                        <el-radio :label="0">男</el-radio>
                        <el-radio :label="1" style="margin-left: 10px">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="所属院系" required style="margin-top: 5px">
                    <el-col :span="11">
                        <el-form-item prop="collegeId">
                            <el-select filterable v-model="activityInfo.collegeId" placeholder="请选择学院"
                                @change="colleageChanged(activityInfo.collegeId)">
                                <el-option v-for="(item, index) in collegeAndMajor" :key="index"
                                    :label="item.collegeName" :value="item.collegeId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col class="lines" :span="2" style="text-align: center">-</el-col>
                    <el-col :span="11">
                        <el-form-item prop="majorId">
                            <el-select v-model="activityInfo.majorId" placeholder="请选择专业">
                                <el-option filterable v-for="(item, index) in majorList" :key="index" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="班级" prop="sClass" size="samll" class="inpbox">
                    <el-input v-model="activityInfo.sClass"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button id="elbox" type="primary" @click="submitForm('activityInfo')"
                        v-loading.fullscreen.lock="fullscreenLoading">立即报名</el-button>
                    <el-button id="resetForm" @click="resetForm('activityInfo')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import {
    getQualifications,
    addJoinActivity,
    checkActivityStatus,
    getCurrentTime,
} from "../../api/activity";
import CryptoJS from "crypto-js";
export default {
    name: "Activitie",
    props: {
        data: {
            type: Object,
            default: () => { }
        },
    },
    data() {
        return {
            activityData: {},
            dialogVisible: false,
            collegeAndMajor: [],
            majorList: [],
            activityInfo: {
                userId: "",
                sClass: "",
                activityId: "",
                name: "",
                alimit: 0, //活动人数限制
                gender: 0,
                phone: "",
                majorId: "",
                collegeId: "",
            },
            fullscreenLoading: false, //活动报名表单的控制加载
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入姓名",
                        trigger: "blur",
                    },
                    {
                        min: 2,
                        max: 5,
                        message: "长度在 2 到 5 个字符",
                        trigger: "blur",
                    },
                ],
                alimit: [
                    {
                        type: 'number',
                        min: 0,
                        message: '数值不能小于0',
                        trigger: 'blur'
                    }
                ],
                collegeId: [
                    {
                        required: true,
                        message: "请选择学院",
                        trigger: "blur",
                    },
                ],
                majorId: [
                    {
                        required: true,
                        message: "请选择专业",
                        trigger: "blur",
                    },
                ],
                phone: [
                    {
                        required: true,
                        message: "请输入手机号",
                        trigger: "blur",
                    },
                    {
                        pattern: /^1[3456789]\d{9}$/,
                        message: "手机号码格式不正确",
                    },
                ],
                gender: [
                    {
                        required: true,
                        message: "请选择性别",
                        trigger: "blur",
                    },
                ],
                sclass: [
                    {
                        required: true,
                        message: "请输入班级",
                        trigger: "blur",
                    },
                    {
                        min: 3,
                        message: "长度最少3字符",
                        trigger: "blur",
                    },
                ],
            },
            intervalId: null, // 用于存储定时器的 ID
            strIdReady: false,

        }
    },
    computed: {
        buttonType() {
            const status = this.data.status
            const arr = ['info', 'success', 'primary', 'danger']
            return arr[status]
        },
        currentTime() {
            return this.$store.state.nowTime
        }
    },
    watch: {
        data: {
            immediate: true,
            handler(newValue) {
                this.activityData = newValue
                // setInterval(this.fetchData(this.activityData), 1000);
                // this.fetchData(this.activityData)
                // this.startInterval();
            },
            deep: true
        },
        currentTime: {
            immediate: true,
            handler(newValue) {
                if (JSON.stringify(this.activityData) != "{}") {
                    this.fetchData(this.activityData)
                }
            },
            deep: true
        },
    },
    mounted() {
        this.getUserId();
        this.getColInfo();
    },
    beforeDestroy() {
        // 清除之前的定时器
        if (this.intervalId) {
            clearInterval(this.intervalId);
        }
    },
    methods: {
        startInterval() {
            // 清除之前的定时器
            if (this.intervalId) {
                clearInterval(this.intervalId);
            }
            // 创建新的定时器
            this.intervalId = setInterval(() => {
                this.fetchData(this.activityData);
            }, 1000);
        },
        resetForm(activityInfo) {
            this.$refs[activityInfo].resetFields();
        },
        formattedDate(time) {
            const date = new Date(time);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, "0");
            const day = date.getDate().toString().padStart(2, "0");
            const hours = date.getHours().toString().padStart(2, "0");
            const minutes = date.getMinutes().toString().padStart(2, "0");
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        },
        getCurrentTime() {
            return new Promise((resolve) => {
                getCurrentTime().then((res) => {
                    if (res.code === 20000) {
                        this.currentTime = res.data.date;
                    }
                    resolve(res.data.date);
                });
            })
        },
        async fetchData(activity) {
            // await this.getCurrentTime();
            activity.isCountDown = false;
            if (
                new Date(this.currentTime).getTime() >
                new Date(activity.joinStart).getTime() &&
                new Date(this.currentTime).getTime() <
                new Date(activity.joinEnd).getTime()
            ) {
                //报名中
                checkActivityStatus(activity.id)
                    .then((res) => {
                        if (res.code === 20000) {
                            activity.joinStatus = res.data.status;
                        }
                    })
            } else if (
                new Date(this.currentTime).getTime() >
                new Date(activity.joinEnd).getTime() &&
                new Date(this.currentTime).getTime() <
                new Date(activity.activityStart).getTime()
            ) {
                activity.joinStatus = -1;
            } else if (activity.status === 3) {
                activity.joinStatus = -2;
            } else {
                //不可报名显示倒计时
                activity.isCountDown = true;
            }
            this.$forceUpdate()
        },
        eventEnded() {
            this.$message.warning(
                "报名已经结束，但请继续关注我们的后续活动，下次机会不要错过哦！"
            );
        },
        handleOtherAction(activityId) {
            this.dialogVisible = true; // 打开对话框
            this.activityInfo.activityId = activityId;
            const activity = this.activityData
            if (activity) {
                activity.isDistinguish = !activity.isDistinguish; // 区分活动
            }
        },
        handleClose(done) {
            done();
            // this.$confirm('确认关闭？')
            //   .then(_ => {
            //     done();
            //   })
            //   .catch(_ => { });
        },
        colleageChanged(value) {
            for (let i = 0; i < this.collegeAndMajor.length; i++) {
                if (this.collegeAndMajor[i].collegeId === value) {
                    this.majorList = this.collegeAndMajor[i].majorList;
                    this.activityInfo.majorId = "";
                }
            }
        },
        getColInfo() {
            this.$store
                .dispatch("queryCollege")
                .then(() => {
                    this.collegeAndMajor = this.$store.state.collegeAndMajor;
                    for (let i = 0; i < this.collegeAndMajor.length; i++) {
                        if (
                            this.collegeAndMajor[i].collegeId === this.activityInfo.collegeId
                        ) {
                            this.majorList = this.collegeAndMajor[i].majorList;
                        }
                    }
                })
                .catch((error) => {
                    console.error("获取学院专业列表失败", error);
                });
        },
        tosee() {
            //查看报名
            this.$router.push(`/userInfoForm`);
            this.$message.success("请准时参与");

            // this.dialogVisible = true; // 打开对话框
        },
        getUserId() {
            //获取用户id
            this.$store.dispatch("queryUser").then(() => {
                this.userId = this.$store.state.userInfo.id;
                this.activityInfo.userId = this.userId;

                if (this.activityId !== null && this.userId !== null) {
                    this.strIdReady = true;
                    this.encryptMD5();
                }
                //console.log(this.$store.state.userInfo.id); // 这里应该能获取到数据
            });
        },

        encryptMD5() {
            this.strId = this.activityId + this.userId;
            this.encryptedStr = CryptoJS.MD5(this.strId).toString();
            // 在控制台输出加密后的字符串
        },
        getQualification() {
            getQualifications(this.activityId, this.encryptedStr).then((res) => {
                if (res.code === 20000 || res.code === 20001) {
                    console.log("Success:", res.message); // 打印成功消息
                } else {
                    this.$message.error(res.message || "获取资格信息失败");
                }
            });
        },
        openDialog(activityId) {       //抢名额
            this.getUserId();
            this.activityId = activityId; //获取相对应的activityId
            this.activityInfo.activityId = activityId; //报名表单获取相对应的activityId
            this.encryptMD5();
            this.getQualification();
            this.strIdReady = true; // 设置md5ID准备好
            const activity = this.activityData
            if (activity) {
                activity.isDistinguish = !activity.isDistinguish; // 区分活动
            }
            this.$message.success("已抢到报名资格，请尽快提交报名表，15分钟后失效");
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 检查alimit值是否大于15，如果大于则不发送请求
                    if (this.activityInfo.alimit && this.activityInfo.alimit > 15) {
                        this.$message.warning("alimit值已超过15，不再发送请求");
                        return; // 终止方法执行
                    }
                    addJoinActivity(this.activityInfo).then((res) => {
                        if (res.code === 20000) {
                            this.activityInfo.alimit += 1;
                            this.fullscreenLoading = true;
                            setTimeout(() => {
                                this.fullscreenLoading = false;
                            }, 2000);  // 提交后加载2秒再完成，避免因网络不好而频繁点击
                            this.$message.success("报名成功！");
                            this.$router.push("/");
                        } else {
                            this.$message.error(res.data.message);
                        }
                    });
                } else {
                    this.$message.error("请检查是否输入正确的数据");
                }
            });
            this.dialogVisible = false; // 打开对话框
        },
        //前往活动详细页
        goInDetail(id){
          this.$router.push(`/activitieDetails?id=${id}`)
        }
        // goActivitie(e) {
        //     // this.$$emit("activitie-click", e)
        // }
    }
}
</script>

<style scoped>
p {
    margin: 0;
    padding: 0;
}

.activitie-box {
    flex: 1;
    min-width: 350px;
    background: white;
    border-radius: 8px;
    padding: 20px;
    transition: all 0.3s;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
    box-sizing: border-box;
}

.activitie-box:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.activitie-title {
    font-size: 18px;
    color: #333;
    margin: 0 0 15px 0;
    font-weight: 600;
}

.flex {
    display: flex;
    gap: 8px;
    font-size: 14px;
    color: #666;
    margin: 12px 0;
}

.flex p:first-child {
    color: #333;
    font-weight: 500;
    min-width: 70px;
}

.activitie-button-box {
    margin-top: 20px;
    text-align: center;
}

.el-button {
    padding: 8px 20px;
    font-size: 14px;
    border-radius: 6px;
    transition: all 0.3s;
}

.el-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

@media (max-width: 768px) {
    .activitie-box {
        width: 100%;
        margin: 10px 0;
    }

    .flex {
        flex-direction: column;
        gap: 4px;
    }
}
</style>
